package com.example.shopping1902.me;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.example.shopping1902.R;

import java.util.ArrayList;
import java.util.List;

public class LocalImageActivity extends AppCompatActivity {
    GridView gv;
    List<String>list;
    private LocalImageAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_image);
        gv = findViewById(R.id.localimg_gv);
        //数据源：本地图片地址的集合
        list = new ArrayList<>();
        //适配器
         adapter = new LocalImageAdapter(this, list);
         gv.setAdapter(adapter);
         //加载数据源
        loadData();
        setItemClick();
    }

    private void setItemClick() {
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String fpath = list.get(position);
                Intent intent = new Intent();
                intent.putExtra("fpath",fpath);
                setResult(Activity.RESULT_OK,intent);
            }
        });
    }

    //加载本地数据
    private void loadData() {
        //1.获取内容接收者的对象
        ContentResolver resolver = getContentResolver();
        //2获取本地图片存储地址
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        //3.开始查找
        Cursor cursor = resolver.query(uri, null, null, null, null);
        //4.遍历cursor
        while (cursor.moveToNext()){
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            list.add(path);
        }
        //5.数据发生变化了，提示更新
        adapter.notifyDataSetChanged();
    }
}
